package leetcode;

public class Remove_Linked_List_Elements {
	class ListNode {
	     int val;
	     ListNode next;
	     ListNode(int x) { val = x; }
	 }
	public ListNode removeElements(ListNode head, int val) {
		if(head==null)
			return head;
		ListNode pre = null, current = head;
		while(current!=null){
			if (current.val==val) {
				if(pre!=null){
					pre.next = current.next;
					current = current.next;
				} else{
					head = current.next;
					current = head;
				}
			}
			else{
				pre = current;
				current = current.next;
			}
		}
		
		return head;
		
	}
	public static void main(String[] argsStrings){
		Remove_Linked_List_Elements remove_Linked_List_Elements = new Remove_Linked_List_Elements();
		ListNode head = remove_Linked_List_Elements.new ListNode(1);
		head.next = remove_Linked_List_Elements.new ListNode(2);
//		head.next.next = remove_Linked_List_Elements.new ListNode(6);
//		head.next.next.next = remove_Linked_List_Elements.new ListNode(5);
//		head.next.next.next.next = remove_Linked_List_Elements.new ListNode(6);
//		
		head = remove_Linked_List_Elements.removeElements(head, 2);
		System.out.println(head);
		while(head!=null){
			System.out.print(" "+head.val);
			head = head.next;
		}
		
	}
}
